#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能童话书 - API路由模块
"""

import logging
from flask import request, jsonify
from intelligent_story_engine import IntelligentStoryEngine

logger = logging.getLogger(__name__)

class EnhancedStoryAPI:
    """增强版故事API类"""
    
    def __init__(self, story_engine, app_stats):
        self.story_engine = story_engine
        self.app_stats = app_stats
    
    def generate_intelligent_story(self):
        """智能故事生成接口"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({"error": "缺少请求数据"}), 400
            
            logger.info(f"🎯 收到智能故事生成请求: {data}")
            
            # 构建故事参数
            story_params = {
                "theme": data.get("theme", "友谊"),
                "characters": data.get("characters", ["小兔子", "小松鼠"]),
                "age_group": data.get("age_group", "6-8岁"),
                "emotional_focus": data.get("emotional_focus", "friendship"),
                "story_length": data.get("story_length", "medium"),
                "educational_goals": data.get("educational_goals", []),
                "interaction_level": data.get("interaction_level", "medium")
            }
            
            # 生成智能故事
            if self.story_engine:
                result = self.story_engine.generate_intelligent_story(story_params)
                self.app_stats["total_stories"] += 1
                
                logger.info(f"✅ 成功生成智能故事: {result['title']}")
                return jsonify({
                    "success": True,
                    "data": result,
                    "message": "🎭 智能故事生成成功！",
                    "engine_type": "Enhanced Intelligence Engine"
                })
            else:
                return self._generate_fallback_response(story_params)
                
        except Exception as e:
            logger.error(f"❌ 智能故事生成失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e),
                "message": "故事生成失败，请稍后重试"
            }), 500
    
    def rate_story(self):
        """故事评分接口"""
        try:
            data = request.get_json()
            rating = data.get("rating", 5)
            story_id = data.get("story_id", "")
            feedback = data.get("feedback", "")
            
            # 更新平均评分
            if self.app_stats["total_stories"] > 0:
                current_total = self.app_stats["average_rating"] * (self.app_stats["total_stories"] - 1)
                self.app_stats["average_rating"] = (current_total + rating) / self.app_stats["total_stories"]
            
            logger.info(f"⭐ 收到故事评分: {rating}/5 反馈: {feedback}")
            
            return jsonify({
                "success": True,
                "message": "感谢您的宝贵评分！🙏",
                "average_rating": round(self.app_stats["average_rating"], 2),
                "total_ratings": self.app_stats["total_stories"]
            })
            
        except Exception as e:
            logger.error(f"❌ 评分处理失败: {e}")
            return jsonify({"success": False, "error": str(e)}), 500
    
    def get_system_status(self):
        """获取系统状态"""
        try:
            uptime = (datetime.now() - self.app_stats["start_time"]).total_seconds()
            
            status = {
                "system_status": "运行正常",
                "engine_status": "智能引擎已就绪" if self.story_engine else "引擎未初始化",
                "total_stories": self.app_stats["total_stories"],
                "user_sessions": self.app_stats["user_sessions"],
                "average_rating": round(self.app_stats["average_rating"], 2),
                "uptime_seconds": int(uptime),
                "uptime_formatted": f"{int(uptime//3600)}小时{int((uptime%3600)//60)}分钟",
                "features": [
                    "🧠 智能三幕式故事结构",
                    "🎭 深度角色心理系统",
                    "💝 情感智能分析",
                    "🔗 情节连贯性检查",
                    "🎯 交互式故事分支",
                    "📊 故事质量评估"
                ],
                "timestamp": datetime.now().isoformat()
            }
            
            return jsonify(status)
            
        except Exception as e:
            logger.error(f"❌ 获取系统状态失败: {e}")
            return jsonify({"error": str(e)}), 500
    
    def _generate_fallback_response(self, params):
        """生成备用响应"""
        fallback_story = {
            "title": f"{params['characters'][0]}的智能冒险",
            "story": f"""从前，有一只叫{params['characters'][0]}的小动物，它非常聪明和勇敢。

有一天，{params['characters'][0]}遇到了一个有趣的问题需要解决。它仔细思考，运用自己的智慧，一步步分析情况。

经过努力和坚持，{params['characters'][0]}不仅解决了问题，还学到了宝贵的经验。从此，它变得更加自信和智慧。

这个故事告诉我们：遇到困难时，要保持冷静，用智慧去思考和解决问题。""",
            "characters": [{"name": params['characters'][0], "traits": ["智慧", "勇敢", "善良"]}],
            "educational_insights": ["智慧比力量更重要", "坚持思考能解决问题"],
            "quality_score": {"overall": 0.75},
            "generated_at": datetime.now().isoformat(),
            "metadata": {"engine": "Fallback", "intelligence_level": "Basic"}
        }
        
        return jsonify({
            "success": True,
            "data": fallback_story,
            "message": "使用备用引擎生成故事",
            "engine_type": "Fallback Engine"
        })